import { getItem } from '@/components/Session.vue';

class WebSocketService {
    constructor() {
        this.connections = new Map();
        this.messageHandlers = new Map();
    }

    // 创建新的 WebSocket 连接
    connect(type, username) {
        if (this.connections.has(type)) {
            return this.connections.get(type);
        }

        const ws = new WebSocket(`ws://47.111.115.11:8080/${type}/${username}`);
        
        ws.onopen = () => {
            console.log(`${type} WebSocket连接已建立`);
        };

        ws.onmessage = (event) => {
            const handlers = this.messageHandlers.get(type) || [];
            handlers.forEach(handler => handler(event.data));
        };

        ws.onerror = (error) => {
            console.error(`${type} WebSocket错误:`, error);
        };

        ws.onclose = () => {
            console.log(`${type} WebSocket连接已关闭`);
            this.connections.delete(type);
            // 5秒后尝试重新连接
            setTimeout(() => this.connect(type, username), 5000);
        };

        this.connections.set(type, ws);
        return ws;
    }

    // 添加消息处理器
    addMessageHandler(type, handler) {
        if (!this.messageHandlers.has(type)) {
            this.messageHandlers.set(type, []);
        }
        this.messageHandlers.get(type).push(handler);
    }

    // 移除消息处理器
    removeMessageHandler(type, handler) {
        if (this.messageHandlers.has(type)) {
            const handlers = this.messageHandlers.get(type);
            const index = handlers.indexOf(handler);
            if (index > -1) {
                handlers.splice(index, 1);
            }
        }
    }

    // 关闭特定类型的连接
    disconnect(type) {
        if (this.connections.has(type)) {
            this.connections.get(type).close();
            this.connections.delete(type);
        }
    }

    // 关闭所有连接
    disconnectAll() {
        this.connections.forEach(ws => ws.close());
        this.connections.clear();
    }
}

// 创建单例实例
const websocketService = new WebSocketService();

// 导出实例
export default websocketService; 